#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#define JSON_RESPONSE "Content-Type: application/json;charset=UTF-8\r\n\r\n"

void urldecode(char *dst, const char *src) {
    char a, b;
    while (*src) {
        if ((*src == '%') && (a = src[1]) && (b = src[2]) && isxdigit(a) && isxdigit(b)) {
            if (a >= 'a') a -= 'a'-'A';
            if (a >= 'A') a -= ('A' - 10);
            else a -= '0';
            if (b >= 'a') b -= 'a'-'A';
            if (b >= 'A') b -= ('A' - 10);
            else b -= '0';
            *dst++ = 16*a+b;
            src += 3;
        } else if (*src == '+') {
            *dst++ = ' ';
            src++;
        } else {
            *dst++ = *src++;
        }
    }
    *dst = '\0';
}

int main() {
    printf(JSON_RESPONSE);
    
    char *method = getenv("REQUEST_METHOD");
    char *query_string = getenv("QUERY_STRING");
    
    // 记录访问日志
    FILE *log = fopen("/tmp/cgi_access.log", "a");
    if (log) {
        fprintf(log, "[%ld] %s %s\n", time(NULL), method ? method : "NULL", query_string ? query_string : "NULL");
        fclose(log);
    }
    
    if (!method || strcmp(method, "GET") != 0) {
        printf("{\"status\":\"error\",\"msg\":\"只支持GET请求\",\"received_method\":\"%s\"}", method ? method : "NULL");
        return 1;
    }
    
    if (!query_string) {
        printf("{\"status\":\"success\",\"msg\":\"测试成功，但没有查询参数\"}");
        return 0;
    }
    
    // 解析参数
    char device[32] = {0};
    char action[32] = {0};
    char value[32] = {0};
    
    char decoded_query[256];
    urldecode(decoded_query, query_string);
    
    char *token = strtok(decoded_query, "&");
    while (token) {
        char *eq = strchr(token, '=');
        if (eq) {
            *eq = '\0';
            char *name = token;
            char *val = eq + 1;
            
            if (strcmp(name, "device") == 0) strncpy(device, val, 31);
            else if (strcmp(name, "action") == 0) strncpy(action, val, 31);
            else if (strcmp(name, "value") == 0) strncpy(value, val, 31);
        }
        token = strtok(NULL, "&");
    }
    
    time_t current_time = time(NULL);
    
    // 模拟设备响应
    if (strcmp(device, "led") == 0) {
        if (strcmp(action, "on") == 0) {
            printf("{\"status\":\"success\",\"msg\":\"LED已开启\",\"device\":\"led\",\"action\":\"on\",\"timestamp\":%ld}", current_time);
        }
        else if (strcmp(action, "off") == 0) {
            printf("{\"status\":\"success\",\"msg\":\"LED已关闭\",\"device\":\"led\",\"action\":\"off\",\"timestamp\":%ld}", current_time);
        }
        else if (strcmp(action, "brightness") == 0 && strlen(value) > 0) {
            printf("{\"status\":\"success\",\"msg\":\"亮度设置成功\",\"device\":\"led\",\"action\":\"brightness\",\"value\":%s,\"timestamp\":%ld}", value, current_time);
        }
        else {
            printf("{\"status\":\"error\",\"msg\":\"不支持的LED操作\",\"action\":\"%s\"}", action);
        }
    }
    else if (strcmp(device, "fan") == 0) {
        if (strcmp(action, "on") == 0) {
            printf("{\"status\":\"success\",\"msg\":\"风扇已开启\",\"device\":\"fan\",\"action\":\"on\",\"timestamp\":%ld}", current_time);
        }
        else if (strcmp(action, "close") == 0) {
            printf("{\"status\":\"success\",\"msg\":\"风扇已关闭\",\"device\":\"fan\",\"action\":\"close\",\"timestamp\":%ld}", current_time);
        }
        else if (strcmp(action, "speed") == 0 && strlen(value) > 0) {
            printf("{\"status\":\"success\",\"msg\":\"风速设置成功\",\"device\":\"fan\",\"action\":\"speed\",\"value\":%s,\"timestamp\":%ld}", value, current_time);
        }
        else {
            printf("{\"status\":\"error\",\"msg\":\"不supported的风扇操作\",\"action\":\"%s\"}", action);
        }
    }
    else if (strcmp(device, "sensor") == 0) {
        if (strcmp(action, "read") == 0) {
            // 生成模拟传感器数据
            srand(current_time);
            float temperature = 22.0 + (rand() % 130) / 10.0; // 22.0-35.0°C
            float humidity = 40.0 + (rand() % 400) / 10.0;    // 40.0-80.0%
            
            printf("{\"status\":\"success\",\"temperature\":%.1f,\"humidity\":%.1f,\"timestamp\":%ld}", 
                   temperature, humidity, current_time);
        }
        else {
            printf("{\"status\":\"error\",\"msg\":\"不支持的传感器操作\",\"action\":\"%s\"}", action);
        }
    }
    else if (strlen(device) == 0) {
        printf("{\"status\":\"success\",\"msg\":\"CGI测试成功\",\"query_string\":\"%s\",\"timestamp\":%ld}", query_string, current_time);
    }
    else {
        printf("{\"status\":\"error\",\"msg\":\"不支持的设备类型\",\"device\":\"%s\"}", device);
    }
    
    return 0;
}
